from emmett import App, request, response
from emmett.orm import Database, Model, Field
from emmett.tools import service, requires

# 创建应用实例
app = App(__name__)

# 配置数据库
app.config.db.uri = "postgres://username:password@hostname/dbName"
db = Database(app, auto_connect=True, auto_migrate=True)


# 定义 Task 模型
class Task(Model):
    name = Field.string()
    is_completed = Field.bool(default=False)


# 将数据库绑定到应用
db.define_models(Task)
app.pipeline = [db.pipe]


# 认证函数
def is_authenticated():
    return request.headers.get("api-key") == "foobar"


def not_authorized():
    response.status = 401
    return {'error': 'not authorized'}


# API路由：获取所有任务
@app.route('/api/tasks', methods=['GET'])
@requires(is_authenticated, otherwise=not_authorized)
@service.json
async def get_tasks():
    # 获取所有的任务，分页返回
    page = int(request.query_params.get('page', 1))  # 默认分页页码为 1
    tasks = Task.all().select(paginate=(page, 20))
    return {'tasks': [task.as_dict() for task in tasks]}


# API路由：获取指定任务
@app.route('/api/tasks/<int:pk>', methods=['GET'])
@requires(is_authenticated, otherwise=not_authorized)
@service.json
async def get_task(pk):
    task = Task.get(pk)
    if task:
        return {'id': task.id, 'name': task.name, 'is_completed': task.is_completed}
    return {'error': 'Task not found'}, 404


# API路由：创建新任务
@app.route('/api/tasks', methods=['POST'])
@requires(is_authenticated, otherwise=not_authorized)
@service.json
async def create_task():
    data = await request.body_params  # 获取 POST 请求的 JSON 数据
    name = data.get('name')
    is_completed = data.get('is_completed', False)
    if not name:
        return {'error': 'Name is required'}, 400

    task = Task.create(name=name, is_completed=is_completed)
    return {"id": task.id, "name": task.id.name, "is_completed": task.id.is_completed}, 201

# API路由：更新任务
@app.route('/api/tasks/<int:pk>', methods=['PUT'])
@requires(is_authenticated, otherwise=not_authorized)
@service.json
async def update_task(pk):
    data = await request.body_params  # 获取 PUT 请求的 JSON 数据
    task = Task.get(pk)

    if not task:
        return {'error': 'Task not found'}, 404

    name = data.get('name', task.name)
    is_completed = data.get('is_completed', task.is_completed)

    task.update_record(name=name, is_completed=is_completed)

    return {'id': task.id, 'name': task.name, 'is_completed': task.is_completed}


# API路由：删除任务
@app.route('/api/tasks/<int:pk>', methods=['DELETE'])
@requires(is_authenticated, otherwise=not_authorized)
@service.json
async def delete_task(pk):
    task = Task.get(pk)
    if not task:
        return {'error': 'Task not found'}, 404

    task.delete_record()

    return {}, 204  # 返回空响应，表示删除成功


